package com.xjcs.saplingplan.utils

import android.content.Context
import android.graphics.drawable.Drawable
import android.widget.ImageView
import androidx.annotation.DrawableRes
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.xjcs.saplingplan.R
import java.io.File

/**
 * Glide 图片加载工具类
 * 提供统一的图片加载配置和错误处理
 */
object GlideUtils {

    // 渐变过渡效果工厂
    private val crossFadeFactory = DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(true).build()

    // 默认配置
    private val defaultOptions: RequestOptions by lazy {
        RequestOptions()
            .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
            .skipMemoryCache(false)
            .dontAnimate()
    }

    // 圆形图片配置
    private val circleCropOptions: RequestOptions by lazy {
        defaultOptions.clone()
            .circleCrop()
    }

    // 圆角图片配置
    private fun getRoundedCornersOptions(radius: Int): RequestOptions {
        return defaultOptions.clone()
            .transform(RoundedCorners(radius))
    }

    /**
     * 获取 Glide RequestManager
     */
    private fun with(context: Context): RequestManager {
        return Glide.with(context)
    }

    /**
     * 加载本地资源图片 - 基础方法
     */
    private fun load(
        context: Context,
        @DrawableRes resId: Int,
        imageView: ImageView,
        placeholder: Int = R.drawable.ic_image_placeholder,
        error: Int = R.drawable.ic_image_placeholder,
        isCrossFade: Boolean = true,
        listener: ImageLoadListener? = null
    ) {
        val request = with(context)
            .load(resId)
            .apply(defaultOptions)
            .placeholder(placeholder)
            .error(error)

        if (isCrossFade) {
            request.transition(DrawableTransitionOptions.withCrossFade(crossFadeFactory))
        }

        listener?.let {
            request.addListener(createGlideListener(it))
        }

        request.into(imageView)
    }

    /**
     * 加载网络图片
     */
    private fun loadUrl(
        context: Context,
        url: String?,
        imageView: ImageView,
        placeholder: Int = R.drawable.ic_image_placeholder,
        error: Int = R.drawable.ic_image_placeholder,
        isCrossFade: Boolean = true,
        listener: ImageLoadListener? = null
    ) {
        if (url.isNullOrEmpty()) {
            imageView.setImageResource(error)
            return
        }

        val request = with(context)
            .load(url)
            .apply(defaultOptions)
            .placeholder(placeholder)
            .error(error)

        if (isCrossFade) {
            request.transition(DrawableTransitionOptions.withCrossFade(crossFadeFactory))
        }

        listener?.let {
            request.addListener(createGlideListener(it))
        }

        request.into(imageView)
    }

    /**
     * 加载本地文件图片
     */
    fun loadFile(
        context: Context,
        file: File?,
        imageView: ImageView,
        placeholder: Int = R.drawable.ic_image_placeholder,
        error: Int = R.drawable.ic_image_placeholder,
        listener: ImageLoadListener? = null
    ) {
        if (file == null || !file.exists()) {
            imageView.setImageResource(error)
            return
        }

        with(context)
            .load(file)
            .apply(defaultOptions)
            .placeholder(placeholder)
            .error(error)
            .addListener(createGlideListener(listener))
            .into(imageView)
    }

    /**
     * 加载圆形图片
     */
    fun loadCircle(
        context: Context,
        @DrawableRes resId: Int,
        imageView: ImageView,
        placeholder: Int = R.drawable.ic_image_placeholder,
        error: Int = R.drawable.ic_image_placeholder,
        listener: ImageLoadListener? = null
    ) {
        with(context)
            .load(resId)
            .apply(circleCropOptions)
            .placeholder(placeholder)
            .error(error)
            .addListener(createGlideListener(listener))
            .into(imageView)
    }

    /**
     * 加载圆角图片
     */
    fun loadRoundCorner(
        context: Context,
        @DrawableRes resId: Int,
        imageView: ImageView,
        cornerRadius: Int,
        placeholder: Int = R.drawable.ic_image_placeholder,
        error: Int = R.drawable.ic_image_placeholder,
        listener: ImageLoadListener? = null
    ) {
        with(context)
            .load(resId)
            .apply(getRoundedCornersOptions(cornerRadius))
            .placeholder(placeholder)
            .error(error)
            .addListener(createGlideListener(listener))
            .into(imageView)
    }

    /**
     * 清除图片缓存
     */
    fun clearCache(context: Context) {
        Glide.get(context).clearMemory()
        Thread {
            Glide.get(context).clearDiskCache()
        }.start()
    }

    /**
     * 暂停请求（在列表快速滑动时调用）
     */
    fun pauseRequests(context: Context) {
        with(context).pauseRequests()
    }

    /**
     * 恢复请求
     */
    fun resumeRequests(context: Context) {
        with(context).resumeRequests()
    }

    /**
     * 创建 Glide 监听器
     */
    private fun createGlideListener(listener: ImageLoadListener?): RequestListener<Drawable> {
        return object : RequestListener<Drawable> {
            override fun onLoadFailed(
                e: GlideException?,
                model: Any?,
                target: Target<Drawable>?,
                isFirstResource: Boolean
            ): Boolean {
                listener?.onLoadFailed(e?.message ?: "Unknown error")
                return false
            }

            override fun onResourceReady(
                resource: Drawable?,
                model: Any?,
                target: Target<Drawable>?,
                dataSource: DataSource?,
                isFirstResource: Boolean
            ): Boolean {
                listener?.onLoadSuccess()
                return false
            }
        }
    }

    /**
     * 图片加载监听接口
     */
    interface ImageLoadListener {
        fun onLoadSuccess()
        fun onLoadFailed(error: String)
    }

    /**
     * 简化版的加载方法 - 最常用的场景
     */
    fun loadSimple(context: Context, @DrawableRes resId: Int, imageView: ImageView) {
        load(context, resId, imageView, R.drawable.ic_image_placeholder, R.drawable.ic_image_placeholder)
    }

    fun loadUrlSimple(context: Context, url: String?, imageView: ImageView) {
        loadUrl(context, url, imageView, R.drawable.ic_image_placeholder, R.drawable.ic_image_placeholder)
    }

    fun loadCircleSimple(context: Context, @DrawableRes resId: Int, imageView: ImageView) {
        loadCircle(context, resId, imageView, R.drawable.ic_image_placeholder, R.drawable.ic_image_placeholder)
    }
}